<template>
	<div class="firstClassifyNew lcad">
		<!-- 选择餐点时段 -->
		<blue-button text="新增" :clickEvent="clickAdd" style="text-align: left;"></blue-button>
		<div class="bannerstyle">
			<span>楼层展示样式：</span>
			<div class="banneranim" v-for="(item, index) in SelectedStatedata" :key="index">
				<cirle-select class="stylename" :state="item.index == activeIndex" :clickEvent="CirleSelectedState2.bind(this, item.index)"></cirle-select><span>{{item.text}}</span>
			</div>
		</div>
		<div class="bannerstyle">
			<span>标题是否显示：</span>
			<div class="banneranim">
				<cirle-select class="stylename" :state="flage1" :clickEvent="CirleSelectedState.bind(this,1)"></cirle-select>
			</div>
			<span>宣传图是否显示：</span>
			<div class="banneranim">
				<cirle-select class="stylename" :state="flage2" :clickEvent="CirleSelectedState.bind(this,2)"></cirle-select>
			</div>
		</div>
		<table class="sv-table">
			<tr class="table-th">
				<th>资源位</th>
				<th>标题</th>
				<th>副标题</th>
				<th>宣传图片</th>
				<th>图片跳转页</th>
				<th>商品code</th>
				<th>更新日期</th>
				<th>操作</th>
			</tr>
			<tr class="table-tr" v-for="(item,index) in dataList" :key="index">
				<td>{{relPositionfn(item.relPosition)}}</td>
				<td>{{item.relTitle?item.relTitle:"--"}}</td>
				<td>{{item.relSubtitle?item.relSubtitle:"--"}}</td>
				<td><img v-if="item.publicityPicture" :src="item.publicityPicture" /><span v-if="!item.publicityPicture">--</span></td>
				<td>{{item.extendField?urlfn(item.extendField):"--"}}</td>
				<td>{{item.goodsCode?item.goodsCode:"--"}}</td>
				<td>{{item.updateTm?myGetTime(item.updateTm):myGetTime(item.createTm)}}</td>
				<td style="text-align: center;">
					<gray-button class="grayBtn" :text="'更新'" :clickEvent="clickEdit.bind(this, index,item)"></gray-button>
					<gray-button class="grayBtn" :text="'删除'" :clickEvent="deleteGoods.bind(this, item)"></gray-button>
				</td>
			</tr>
		</table>
		<edit-model ref="editModel" title="分类推荐" :closeCallback="editModelCloseEvent">
			<div class="slot-notice food" style="text-align: left;" slot="main">
				<div class="textleft" v-if="uploadType == 'add'">
					<p class="eidt-slot-title">资源位：</p>
					<div style="display: inline-block;">
						<label style="display: inline-block;width: 100px;">
                        	<input type="radio" name="tuiguang" :checked="type === 'TITLE'" @click="changeType(0)" />标题位
                        </label>
						<label style="display: inline-block;width: 100px">
                        	<input type="radio" name="tuiguang" :checked="type === 'IMAGE'" @click="changeType(1)" />图片位
                        </label>
						<label style="display: inline-block;width: 100px">
                        	<input type="radio" name="tuiguang" :checked="type === 'GOODS'" @click="changeType(2)" />商品位
                        </label>
					</div>
				</div>
				<div class="textleft" v-if="type === 'TITLE'">
					<p class="eidt-slot-title" style="width: 50%;">主标题<span class="required">*</span>：</p>
					<input type="text" style="width: 50%;" v-model="relTitle" />
				</div>
				<div class="textleft" v-if="type === 'TITLE'">
					<p class="eidt-slot-title" style="width: 50%;">副标题<span class="required">*</span>：</p>
					<input type="text" style="width: 50%;" v-model="relSubtitle" />
				</div>

				<div v-if="type === 'GOODS'">
					<p class="eidt-slot-title">宣传图片</p>
					<div class="upload-box">
						<img-upload :deleteCallback="deleteImgCallback" ref="bannerImg" :imgShowList="getBannerUrl ? [getBannerUrl] : []" compressStrategy='size' :maxCompressWidth='240' :maxCompressHeight='240'>
						</img-upload>
					</div>
				</div>
				<div class="textleft" v-if="type === 'GOODS'">
					<p class="eidt-slot-title" style="width: 50%;">商品编码<span class="required">*</span>：</p>
					<input type="text" style="width: 50%;" v-model="goodsCode" @click="showMenu()" readonly />
				</div>

				<div v-if="type === 'IMAGE'">
					<p class="eidt-slot-title">宣传图片<span class="required">*</span></p>
					<!--<p style="color: red;font-size: 12px;">固定式图片尺寸375*140，沉浸式图片尺寸375*290</p>-->
					<div class="upload-box">
						<img-upload :deleteCallback="deleteImgCallback" ref="bannerImg2" :imgShowList="getBannerUrl2 ? [getBannerUrl2] : []">
						</img-upload>
					</div>
				</div>
				<div class="textleft" v-if="type === 'IMAGE'">
					<p class="eidt-slot-title" style="width: 50%;">自定义跳转链接<span class="required">*</span>：</p>
					<page-path :changeEvent="changeEvent" :defaultChooseProps="valueArray" rootSelector="#edit-model-box"></page-path>
				</div>

				<div class="fabu-box" style="text-align: center;">
					<blue-button text="发布" :clickEvent="upLoadImg"></blue-button>
					<!--<gray-button text="取消" :clickEvent="hideModel" class="confimBtn"></gray-button>-->
				</div>
			</div>
			<div slot="slide">
				<search-encode ref="searchModel" @getgoodscodedata="getgoodscode"></search-encode>
			</div>
		</edit-model>
		<m-toast ref="toast"></m-toast>
		<m-dialog ref="dialog"></m-dialog>
	</div>

</template>

<script>
	import BlueButton from "../../../edit-components/BlueButton";
	import SearchEncode from "../../../edit-components/SearchProduct";
	import getDate from "./getGoodsDate.js";
	import madd from "./add.js";
	import medit from "./edit.js";
	import deleteGoods from './delete.js';
	import GrayButton from "../../../edit-components/GrayButton";
	import imgUpload from "../../../real-components/ImgUpload2";
	import EditModel from "../../../edit-components/EditModel";
	import Toast from "../../../edit-components/Toast";
	import Dialog from "../../../edit-components/Dialog";
	import PagePath from "../../../edit-components/PagePath";
	import CirleSelect from "../../../edit-components/CirleSelect";
	import { getPageNameOrVirtualPageName } from "../../../utils/getPageName";
	export default {
		props: {
			relGroup: {
				type: String,
				default: ""
			}
		},
		data() {
			return {
				dataList: [],
				uploadType: '',
				imgUrl: "",
				imgUrl2: "",
				getBannerUrl: '',
				getBannerUrl2: '',
				type: 'TITLE',
				relTitle: '', //主标题
				relSubtitle: '', //副标题
				goodsCode: '', //商品编码
				editItem: null,
				//跳转路径配置二级联动（数据模拟）
				selectedUrl: "",
				flage1: true,
				flage2: true,
				storeCode: "",
				valueArray: [],
				//楼层广告样式
				SelectedStatedata: [{
					index: 0,
					text: "固定式(图片位图片尺寸375*140)"
				}, {
					index: 1,
					text: "沉浸式(图片位图片尺寸375*290)"
				}],
				activeIndex: 0,
			}
		},
		components: {
			"blue-button": BlueButton,
			"search-encode": SearchEncode,
			"gray-button": GrayButton,
			"img-upload": imgUpload,
			"edit-model": EditModel,
			"m-toast": Toast,
			"m-dialog": Dialog,
			"page-path": PagePath,
			"cirle-select": CirleSelect,
		},
		computed: {
			myDateList() {
				return this.dataList;
			},
			pageName() {
				return getPageNameOrVirtualPageName();
			},
		},
		methods: {
			//获取门店code
			getShopCode() {
				this.storeCode = localStorage.getItem("storeCode");
			},
			//获取子组件路径的值
			changeEvent(data) {
				this.selectedUrl = data
			},
			urlfn(item) {
				if(JSON.parse(item).url) {
					return JSON.parse(item).url.UIContent
				} else {
					return "--"
				}
			},
			/*获取商品编码*/
			showMenu() {
				this.$refs.editModel.showSlideMenu();
				this.$refs.searchModel.hideModel();
			},
			getgoodscode(msg) {
				this.goodsCode = msg;
			},
			errorToast(msg, duration = 1000) {
				this.$refs.toast.toast(msg, duration);
			},
			//显示是什么商品位
			relPositionfn(item) {
				if(item == "TITLE") {
					return "标题位"
				} else if(item == "IMAGE") {
					return "图片位"
				} else if(item == "GOODS") {
					return "商品位"
				}
			},
			//模态框关闭后的回调事件
			editModelCloseEvent() {
				this.getDateList()
			},
			/*数据排序*/
			dataRank(data) {
				let arrey1 = []
				let arrey2 = []
				let arrey3 = []
				let arrey4 = []
				let arrey5 = []
				for(var i = 0; i < data.length; i++) {
					if(data[i].relPosition == 'TITLE') {
						arrey1.push(data[i])
					} else if(data[i].relPosition == 'IMAGE') {
						arrey2.push(data[i])
					} else if(data[i].relPosition == 'GOODS') {
						arrey3.push(data[i])
					}
				}
				arrey4 = arrey1.concat(arrey2)
				arrey5 = arrey4.concat(arrey3)
				return arrey5
			},
			//数据渲染
			getDateList() {
				let callback = (data) => {
					this.dataList = this.dataRank(data);
				}
				getDate(callback, this.relGroup);
			},
			myGetTime(param) {
				if(param) {
					let date = new Date(param);
					let year = date.getFullYear();
					let month = checkTime(date.getMonth() + 1);
					let day = checkTime(date.getDate());
					let hour = date.getHours();
					let min = checkTime(date.getMinutes());
					let sec = checkTime(date.getSeconds());
					let str = '';
					let mHour = 0;
					if(0 < Number(hour) && Number(hour) < 12) {
						mHour = hour;
						str = '上午'
					} else {
						mHour = Number(hour) - 12;
						str = '下午'

					}

					function checkTime(i) {
						if(i < 10) {
							i = '0' + i;
						}
						return i;
					}
					return year + '/' + month + '/' + day + '  ' + str + ' ' + mHour + ':' + min;
				} else {
					return '';
				}
			},
			showModel() {
				this.$refs.editModel.showCover();
			},
			hideModel() {
				this.$refs.editModel.hideCover();
			},
			changeType(num) {
				if(this.uploadType == 'add') {
					if(num == 0) {
						this.type = 'TITLE';
					} else if(num == 1) {
						this.type = 'IMAGE';
					} else if(num == 2) {
						this.type = 'GOODS';
					}
				} else {
					if(this.editItem.relPosition == 'TITLE') {
						this.type = 'TITLE';
					}
					if(this.editItem.relPosition == 'IMAGE') {
						this.type = 'IMAGE';
					}
					if(this.editItem.relPosition == 'GOODS') {
						this.type = 'GOODS';
					}
				}
			},
			getParams() {
				var obj = {
					"url": this.selectedUrl
				}
				var str = JSON.stringify(obj);
				if(this.uploadType == 'add') {
					var params = {
						relPosition: this.type,
						storeCode: this.storeCode,
						relGroup: this.relGroup,
					}
					if(this.type == 'GOODS') {
						params.publicityPicture = this.imgUrl;
						params.goodsCode = this.goodsCode;
						params.promotionType = 0
					}
					if(this.type == 'TITLE') {
						params.relSubtitle = this.relSubtitle;
						params.relTitle = this.relTitle;
					}
					if(this.type == 'IMAGE') {
						params.publicityPicture = this.imgUrl2;
						params.extendField = str
					}
				} else if(this.uploadType == 'edit') {
					var params = {
						storeCode: this.storeCode,
						relPosition: this.type,
						rid: this.editItem.rid,
						relGroup: this.relGroup,
					}
					if(this.type == 'GOODS') {
						params.publicityPicture = this.imgUrl;
						params.goodsCode = this.goodsCode;
						params.promotionType = 0
					}
					if(this.type == 'TITLE') {
						params.relSubtitle = this.relSubtitle;
						params.relTitle = this.relTitle;
					}
					if(this.type == 'IMAGE') {
						params.publicityPicture = this.imgUrl2;
						params.extendField = str
					}
				}
				return params;
			},
			add() {
				let params = this.getParams();
				let callback = data => {
					this.dataList = this.dataRank(data);
					this.$refs.editModel.hideCover();
				}
				madd(params, this.relGroup, callback);
			},
			edit() {
				//				relId
				let params = this.getParams();
				let callback = data => {
					this.dataList = this.dataRank(data);
					this.$refs.editModel.hideCover();
				}
				medit(params, this.relGroup, callback);
			},
			clickAdd() {
				if(!getCookie("sessionId")) {
					this.$refs.toast.toast("登录失效，请重新登录");
					return
				}
				this.showModel();
				this.uploadType = 'add';
				this.getBannerUrl = '';
				this.getBannerUrl2 = '';
				this.valueArray = []
				this.selectedUrl = ""
				this.relTitle = ''; //主标题
				this.relSubtitle = ''; //副标题
				this.goodsCode = ''; //商品编码
				if(this.$refs.bannerImg) {
					this.$refs.bannerImg.deleteImg();
				}
				if(this.$refs.bannerImg2) {
					this.$refs.bannerImg2.deleteImg();
				}
			},
			clickEdit(index, item) {
				if(item.relPosition == 'TITLE') {
					this.type = 'TITLE';
				} else if(item.relPosition == 'GOODS') {
					this.type = 'GOODS';
					if(item.publicityPicture){
						this.getBannerUrl = item.publicityPicture;
					    this.imgUrl = item.publicityPicture;
					}else{
						if(this.$refs.bannerImg) {
							this.$refs.bannerImg.deleteImg();
						}
						this.getBannerUrl =''
						this.imgUrl = ''
					}
					
				} else if(item.relPosition == 'IMAGE') {
					this.type = 'IMAGE';
					this.getBannerUrl2 = item.publicityPicture;
					this.imgUrl2 = item.publicityPicture;
					this.valueArray = JSON.parse(item.extendField).url.valueArray
					this.selectedUrl = JSON.parse(item.extendField).url
				}
				this.relTitle = item.relTitle; //主标题
				this.relSubtitle = item.relSubtitle; //副标题
				this.goodsCode = item.goodsCode; //商品编码
				this.uploadType = 'edit';
				this.editItem = item;
				this.showModel();

			},
			provient(mevent) {
				mevent.target.checked = false;
			},
			deleteGoods(item) {
				console.log(item, 'aa');
				let msg = '确定要删除吗？';
				let confirmFn = () => {
					let params = {
						rid: item.rid,
						storeCode: this.storeCode,
						relGroup: this.relGroup
					}
					let callback = data => {
						this.dataList = this.dataRank(data);
					}
					deleteGoods(params, this.relGroup, callback);
				}

				this.infoDialog(msg, confirmFn);

			},
			infoDialog(msg, confirmFn) {
				this.$refs.dialog.dialog({
					msg,
					confirmFn
				});
			},
			async upLoadImg() {
				let flag = this.checkedData();
				if(!flag) {
					return;
				}
				if(this.type == 'TITLE') {
					if(this.uploadType == 'add') {
						this.add();
					} else {
						this.edit();
					}
				} else if(this.type == 'GOODS') {
					let response = await this.$refs.bannerImg.upload();
					if(this.uploadType == 'add') {
						if(response.status === 0) {
							this.errorToast("图片上传失败");
							return;
						}
						/*if(response.status === 2) {
							this.errorToast("请上传图片");
							return;
						}*/
						if(response.status === 1) {
							this.imgUrl = response.data[0];
							this.add();
						}else{
							this.add();
						}
					} else {
						if(response.status === 1) {
							this.imgUrl = response.data[0];
							this.edit();
						} else if(response.status === 2) {
							this.edit();
							/*if(!this.getBannerUrl) {
								this.errorToast("请上传图片");
								return;
							} else {
								this.edit();
							}*/
						}
					}
				} else if(this.type == 'IMAGE') {
					let response2 = await this.$refs.bannerImg2.upload();
					if(this.uploadType == 'add') {
						if(response2.status === 0) {
							this.errorToast("图片上传失败");
							return;
						}
						if(response2.status === 2) {
							this.errorToast("请上传图片");
							return;
						}
						if(response2.status === 1) {
							this.imgUrl2 = response2.data[0];
							this.add();
						}
					} else {
						if(response2.status === 1) {
							this.imgUrl2 = response2.data[0];
							this.edit();
						} else if(response2.status === 2) {
							if(!this.getBannerUrl2) {
								this.errorToast("请上传图片");
								return;
							} else {
								this.edit();
							}

						}
					}
				}
			},
			//验证主标题副标题
			checkedData() {
				let titlearrey = []
				let goodsarrey = []
				let imagearrey = []
				for(var i = 0; i < this.dataList.length; i++) {
					if(this.dataList[i].relPosition == "TITLE") {
						titlearrey.push(this.dataList[i])
					} else if(this.dataList[i].relPosition == "GOODS") {
						goodsarrey.push(this.dataList[i])
					} else if(this.dataList[i].relPosition == "IMAGE") {
						imagearrey.push(this.dataList[i])
					}
				}
				if(this.type == 'TITLE') {
					if(titlearrey.length == 1 && this.uploadType == 'add') {
						this.errorToast("标题位只可新增一个");
						return false;
					}
					if(this.relTitle == '') {
						this.errorToast("请填写标题");
						return false;
					} else if(this.relSubtitle == '') {
						this.errorToast("请填写副标题");
						return false;
					} else {
						return true;
					}

				} else if(this.type == 'GOODS') {
					if(this.goodsCode == '') {
						this.errorToast("请选择商品编码");
						return false;
					} else {
						return true;
					}
				} else if(this.type == 'IMAGE') {
					if(imagearrey.length == 1 && this.uploadType == 'add') {
						this.errorToast("图片位只可新增一个");
						return false;
					}
					if(this.selectedUrl == '') {
						this.errorToast("请选择配置链接");
						return false;
					} else {
						return true;
					}
				}
			},
			//判断是商品还是活动
			deleteImgCallback() {
				this.imgUrl = '';
				this.imgUrl2 = '';
			},
			CirleSelectedState(num) {
				if(num == 1) {
					this.flage1 = !this.flage1;
					this.setEditConfig(this.relGroup, {
						classfyTitle: this.flage1
					}, this.pageName)
				} else if(num == 2) {
					this.flage2 = !this.flage2;
					this.setEditConfig(this.relGroup, {
						classfyImg: this.flage2
					}, this.pageName)
				}
			},
			CirleSelectedState2(index) {
				this.activeIndex = index;
				this.setEditConfig(this.relGroup, {
					lcadStyle: this.activeIndex + ""
				}, this.pageName);
			},
			echo() {
				if(this.getCurrentVDO(this.relGroup, this.pageName).config.classfyTitle === undefined) {
					this.setEditConfig(this.relGroup, {
						classfyTitle: this.flage1
					}, this.pageName)
				} else {
					this.flage1 = this.getCurrentVDO(this.relGroup, this.pageName).config.classfyTitle;
				}
				if(this.getCurrentVDO(this.relGroup, this.pageName).config.classfyImg === undefined) {
					this.setEditConfig(this.relGroup, {
						classfyImg: this.flage2
					}, this.pageName)
				} else {
					this.flage2 = this.getCurrentVDO(this.relGroup, this.pageName).config.classfyImg;
				}
				if(this.getCurrentVDO(this.relGroup, this.pageName).config.lcadStyle === undefined) {
					this.setEditConfig(this.relGroup, {
						lcadStyle: this.activeIndex + ""
					}, this.pageName)
				} else {
					this.activeIndex = this.getCurrentVDO(this.relGroup, this.pageName).config.lcadStyle;
				}
			},

		},

		filters: {
			startTimeFilter: function(time) {
				let date = new Date(time);
				return `${date.getFullYear()}-${date.getMonth() + 1 > 9 ? date.getMonth() + 1:'0' + (date.getMonth() + 1)}-${date.getDate()}  ${date.getHours() > 9 ? date.getHours() : '0' + date.getHours()}:${date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()}`;
			}
		},
		created() {

		},
		mounted() {
			if(!getCookie("sessionId")) {
				this.$refs.toast.toast("登录失效，请重新登录");
			}
			this.$nextTick(() => {
				this.echo();
			})
			this.getDateList();
			this.getShopCode();
		},
		watch: {
			relGroup(newVal) {
				if(!getCookie("sessionId")) {
					this.$refs.toast.toast("登录失效，请重新登录");
				}
				this.getDateList();
				this.getShopCode();
				this.echo();
			}
		}

	}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
	.food-title-box {
		display: flex;
	}
	
	.food-list {
		width: 80px;
		height: 16px;
	}
	
	.food-title {
		font-size: 16px;
		line-height: 16px;
		height: 16px;
	}
	
	.mySelect {
		border: 1px solid #ddd;
		padding: 5px 5px;
		width: 10%;
		height: unset;
		margin-bottom: 10px;
		margin-left: 20px;
	}
	
	.rightBtn {
		margin-left: 20px;
	}
	
	.confimBtn {
		margin-left: 20px;
	}
	
	.grayBtn {
		display: inline-block;
	}
	
	.casor {
		cursor: not-allowed;
	}
	
	.fabu-box {
		display: flex;
		justify-content: center;
		margin-top: 30px;
	}
	
	.casor {
		cursor: not-allowed;
	}
	
	.textleft {
		margin-top: 0.4rem;
	}
	/*新样式1*/
	
	.firstClassifyNew tr td:nth-child(4) {
		width: 80px;
		display: inline-block;
		height: 66px;
		overflow: hidden;
		line-height: 66px;
		border: none
	}
	
	.firstClassifyNew tr td:nth-child(4) img {
		height: 66px;
	}
	
	.firstClassifyNew .bannerstyle {
		text-align: left;
		margin-top: 10px;
		margin-bottom: 15px;
	}
	
	.firstClassifyNew .bannerstyle .banneranim span {
		display: inline-block;
		width: 205px;
	}
	
	.firstClassifyNew .bannerstyle .stylename {
		display: inline-block;
		vertical-align: middle;
		margin: 0px 15px;
	}
	
	.firstClassifyNew .bannerstyle .banneranim {
		display: inline-block;
		margin-right: 15px;
	}
</style>